﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Text;

using StockPoint.Util;

namespace StockPoint
{
    /// <summary>
    /// StockPoint 코드관리.
    /// </summary>
    public class SPCode
    {
        private const string DB_CONN = "server=211.245.21.125;uid=StockPointUser;pwd=%$^@tkdgksrk!@@#;database=StockPoint";
        private static DataTable dt;

        #region " Private Methods "

        /// <summary>
        /// T_Code 정보 메모리에 저장.
        /// </summary>
        private static void LoadCodeTable()
        {
            DBUtil cDBUtil = new DBUtil(DB_CONN);
            dt = cDBUtil.GetDataTable("SELECT * FROM T_Code");
        }

        /// <summary>
        /// Convert DataRow array to DataTable.
        /// </summary>
        private static DataTable GetDataTableFromDataRows(ref DataRow[] cRow)
        {
            if (cRow != null)
            {
                DataTable cTable = dt.Clone();
                foreach (DataRow dr in cRow)
                    cTable.ImportRow(dr);

                return cTable;
            }

            return null;
        }

        #endregion

        #region " DB Code "

        /// <summary>
        /// Code List 검색.
        /// </summary>
        /// <param name="sCodeType">CodeType</param>
        /// <param name="sSort">Sort (ex. Idx DESC)</param>
        public static DataTable GetCodeList(string sCodeType, string sSort = "")
        {
            if (dt == null)
                LoadCodeTable();

            string sFilter = "CodeType='" + sCodeType + "'";

            DataRow[] dr = dt.Select(sFilter, sSort);
            return GetDataTableFromDataRows(ref dr);
        }

        /// <summary>
        /// Code Name 검색.
        /// </summary>
        /// <param name="sCodeType">CodeType</param>
        /// <param name="oCode">Code Value</param>
        public static string GetCodeName(string sCodeType, object oCode)
        {
            if (dt == null)
                LoadCodeTable();

            string sFilter = "CodeType='" + sCodeType + "' AND Code=" + oCode.ToString();

            DataRow[] dr = dt.Select(sFilter);
            if (dr.Length == 1)
                return DBUtil.GetValStr(dr[0], "CodeName");
            else
                return string.Empty;
        }

        #endregion

        #region " Custom Code "

        /// <summary>
        /// Bit to OX.
        /// 1 - O
        /// 0 - X
        /// </summary>
        public static string BitToOX(object value)
        {
            if (Convert.ToInt32(value) == 1)
                return "O";
            else
                return "X";
        }

        #endregion
    }
}
